import { reactive } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { numToMinute } from "@/utils/number";

export const useAudio = (events?: {
  onPlay?: () => void;
  onEnded?: () => void;
  onTimeUpdate?: () => void;
}) => {
  onLoad(() => {
    audioCtx.onPlay(onPlay);
    audioCtx.onPause(onPause);
    audioCtx.onEnded(onEnded);
    audioCtx.onStop(onStop);
    audioCtx.onTimeUpdate(onTimeUpdate);
  });
  onUnload(() => {
    audioCtx.offPlay(onPlay);
    audioCtx.offPause(onPause);
    audioCtx.offEnded(onEnded);
    audioCtx.offStop(onStop);
    audioCtx.offTimeUpdate(onTimeUpdate);
    audioCtx.destroy();
  });

  const onPlay = () => {
    audioData.paused = false;
  };
  const onPause = () => {
    audioData.paused = true;
  };
  const onEnded = () => {
    audioData.paused = true;
    reloadAppAudioTime(0); // 重置进度
    events?.onEnded?.();
  };
  const onStop = () => {
    audioData.paused = true;
    reloadAppAudioTime(0); // 重置进度
  };
  const onTimeUpdate = () => {
    reloadAppAudioTime(audioCtx.currentTime);
    events?.onTimeUpdate?.();
  };

  /**
   * 刷新播放时间、进度
   */
  const reloadAppAudioTime = (time: number) => {
    let currentTime = Number.parseInt(time as any);
    currentTime = Number.isNaN(currentTime) ? 0 : currentTime;
    audioData.currentTime = numToMinute(currentTime);
    const duration = Number.parseInt(audioData.duration as any);
    audioData.percent = Number.isNaN(duration)
      ? 0
      : (currentTime / duration) * 100;
  };

  const audioCtx = uni.createInnerAudioContext();
  const audioData = reactive({
    currentTime: "00:00",
    percent: 0,
    paused: true,
    duration: 0,
  });

  return { audioCtx, audioData };
};
